/*
 * @Description: common API
 * @Author: Bo.LiBo@bshg.com
 * @version: H3.0
 * @Date: 2023-03-14 16:41:55
 * @LastEditTime: 2023-04-06 14:18:33
 */
import { GetRequest, PostRequest, type Response } from '@/utils/request'
import Hashes from 'jshashes'
import { useAuthStore } from '@/store/auth'
import loginHelper from '@/pluginHelper/login'
import { jumpMP, toPage } from '@/utils/mpHelper'
import { safeTrack } from '@/dataReport/dataReportUtil'
import { TrackType, trackEvent } from '@/dataReport/tracks'
const authStore = useAuthStore()
const MD5 = new Hashes.MD5()

export function getServerTime() {
  return GetRequest<string>('/api/wx/healthy')
}

/**
 * 根据gps获取水硬度
 * @param data
 * @returns
 */
export type WaterHardType = {
  avalue: string
  bvalue: string
  province: string
  city: string
  district: string
}

export function getWaterHard(data: { lng: number; lat: number }) {
  const date = new Date()
  return GetRequest<null, WaterHardType>(
    'https://boschqrmp.bshg.com.cn/boschqrapi/bosch/wx/monitoring/details',
    {
      key: date.getTime(),
      sign: MD5.hex('B7BPieJwnfiBJ24xjaaOKdF45A' + date.getTime()),
      ...data,
    },
    { customUrl: true }
  )
}
/**
 * 获取系统公告
 */
export function getAnnouncement() {
  return PostRequest(
    `/api/wx/recipeAnnouncement/list`,
    {
      data: {
        page: 0,
        pageSize: 20,
        sortBy: 1,
      },
    },
    { noAuth: true }
  )
}

export type ChiperData = {
  key: string
  iv: string
}
/**
 * @description: 获取存在云端的key以及iv信息用来加解密wifi以及password数据
 * @return {*}
 */
export function getUserKeyIv() {
  return GetRequest<ChiperData>('/api/wx/province/getUserKeyIv')
}
/**
 * @description: 保存小程序初始化生成的key和iv在云端
 * @param {ChiperData} chiperData
 * @return {*}
 */
export function saveUserKeyIv(chiperData: ChiperData) {
  return PostRequest('/api/wx/province/saveUserKeyIv', chiperData)
}
/**
 * 获取banner轮播信息
 */
export type BannerInfo = {
  actionType: string
  close: number
  endTime: string
  id: number
  imageUrl: string
  landingPage: string
  startTime: string
  state: number
  title: string
  appid: string | null
}
export function getBannerInfo() {
  return GetRequest<BannerInfo[]>(`/api/user/bannerInfo`)
}
/**
 * banner跳转
 */
export function jumpBannerWeb(url: string, backPage: string, actionType: string, appId?: string, buttonId?: string) {
  if (!authStore.isLogin) {
    loginHelper.noCiamIdLogin(undefined, { path: backPage })
    return
  }
  if (actionType === '1' || actionType === '3') {
    toPage(url)
  } else if (actionType === '2') {
    // 微信第三方小程序

    jumpMP(appId as string, url, {})
  }
  if (buttonId) {
    safeTrack(() => {
      trackEvent('check_survey_banner_actionhandler', {}, TrackType.ApplianceDetail, buttonId)
    })
  }
}
